<?php
/*
Copyright (c) 2010 Samuel Stevens

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
if (!defined('INDEX')) {exit("This script cannot be called directly");}

function db_escape($text)
{
	return mysql_real_escape_string($text);
}

class DatabaseException extends Exception
{
	function __construct($msg)
	{
		parent::__construct($msg);
	}
}

class Database
{
	private $db;
	private $config = array();
	private $enabled = False;
	private $queryCount = 0;
	private $dieOnError;
	function __construct($config)
	{
		if (!is_array($config))
			throw new DatabaseException('[Database] Invalid config');
		$this->config = $config;
		$this->dieOnError = (isset($config['DieOnError'] )) ? $config['DieOnError'] : True;
		
		if ($this->config['Enabled'])
		{
			if (isset($this->config['Handle']) && is_resource($this->config['Handle']))
			{
				$this->enabled = True;
				$this->db = $this->config['Handle'];
			}
			else
			{
				$this->enabled = True;
				if (isset($this->config['PConnect']) && $this->config['PConnect'] == True)
					$connect_function = "mysql_pconnect";
				else
					$connect_function = "mysql_connect";
				
				$this->db = $connect_function($this->config['Host'], $this->config['Username'], $this->config['Password']);
				if (!$this->db)
				{
					throw new DatabaseException("Could not connect database: ".mysql_error());
				}
				if (!mysql_select_db($this->config['DB'], $this->db))
				{
					throw new DatabaseException("Could not select database: ".$this->config['DB']." (".mysql_error($this->db).")");
				}
			}
		}
	}
	function query($query, $return_array=True, $collapse_single=True)
	{
		if ($this->enabled == False)
			throw new DatabaseException('Database not enabled');
		//echo "$query\n";
		$result = mysql_query($query, $this->db);
		$this->queryCount++;
		if ($result === False && $this->dieOnError)
		{
			throw new DatabaseException("Database query error: ".mysql_error());
		}
		if ($return_array == True && $result !== True)
		{
			$result_array = array();
			$record;
			while (($record = mysql_fetch_assoc($result)) != False)
			{
				$result_array[] = $record;
			}
			mysql_free_result($result);
			if (count($result_array) == 1 && $collapse_single)
				return $result_array[0];
			else
				return $result_array;
		}
		return $result;
	}
	function &get_query_count()
	{
		return $this->queryCount;
	}
	function get_last_error()
	{
		return mysql_error($this->db);
	}
	function affected_rows()
	{
		return mysql_affected_rows($this->db);
	}
	function last_insert_id()
	{
		return mysql_insert_id($this->db);
	}
	function table_exists($table)
	{
		$query = mysql_query("SHOW TABLES LIKE '$table'");
		if ($query != null && mysql_num_rows($query) > 0)
			return true;
		return false;
	}
	function list_tables()
	{
		$result = $this->query('SHOW TABLES IN `'.$this->config['DB'].'`', false);
		$tables = array();
		while ($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
		return $tables;
	}
	function list_fields($table)
	{
		if (!$this->table_exists($table))
			return array();
		$result = $this->query('SHOW COLUMNS IN `'.$table.'`');
		$fields = array();
		foreach ($result as $field)
		{
			$fields[] = $field['Field'];
		}
		return $fields;
	}
}

//end of file database.php